<template>
  <div class="rolelist">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索和添加栏 -->
    <div>
      <!-- <el-input
        placeholder="请输入内容"
        v-model="query"
        class="input-with-select role_search"
        @keyup.13.native="search"
        clearable
      >
        <el-button slot="append" icon="el-icon-search"></el-button>
      </el-input>-->
      <el-button type="success" plain @click="addRoleDialogFormVisible = true">添加角色</el-button>
    </div>
    <!-- 表格数据展示 -->
    <el-table :data="roleList" style="width: 100%" height="750">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row
            v-for="value1 in scope.row.children"
            :key="value1.id"
            style="border-bottom: 1px dashed #ccc; margin-bottom: 10px"
          >
            <el-col :span="4">
              <el-tag closable :type="''" @close="delRight(scope.row,value1.id)">{{value1.authName}}</el-tag>
            </el-col>
            <el-col :span="20">
              <el-row
                v-for="value2 in value1.children"
                :key="value2.id"
                style="border-bottom: 1px dashed #ccc;margin-bottom: 10px"
              >
                <el-col :span="4">
                  <el-tag
                    closable
                    :type="'warning'"
                    @close="delRight(scope.row,value2.id)"
                  >{{value2.authName}}</el-tag>
                </el-col>
                <el-col :span="20">
                  <el-tag
                    v-for="value3 in value2.children"
                    :key="value3.id"
                    closable
                    :type="'success'"
                    style="margin-right:4px;margin-bottom:6px"
                    @close="delRight(scope.row,value3.id)"
                  >{{value3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" v-show="scope.row.children.length === 0">暂时还没有分配任何权限，请分配权限</el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="编辑" placement="top" transition="el-zoom-in-bottom">
            <el-button type="success" icon="el-icon-edit" plain @click="showRoleEdit(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="分配权限" placement="top" transition="el-zoom-in-bottom">
            <el-button
              type="warning"
              icon="el-icon-s-flag"
              plain
              @click="showGrantDialog(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top" transition="el-zoom-in-bottom">
            <el-button type="danger" icon="el-icon-delete" plain @click="delRole(scope.row.id)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="grantdialogFormVisible">
      <el-tree
        ref="mytree"
        :data="rightList"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="checkedArr"
        :props="defaultProps"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="grantdialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="grantRightSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogFormVisible">
      <el-form :model="addRoleForm" :label-width="'80px'" :rules="rules" ref="addRoleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoleForm.roleDesc" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editRoleDialogFormVisible">
      <el-form :model="editRoleForm" :label-width="'80px'" :rules="rules" ref="editRoleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleForm.roleDesc" autocomplete="off" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllRoleList,
  delRightById,
  grantRightByRole,
  addRole,
  delRoleById,
  editRoleById
} from '@/api/role_api.js'
import { getAllRightList } from '@/api/right_api.js'
export default {
  data () {
    return {
      query: '',
      // 要授权的角色id
      roleId: '',
      // 默认选中的权限
      checkedArr: [],
      // 添加角色对话框
      addRoleDialogFormVisible: false,
      // 编辑角色对话框
      editRoleDialogFormVisible: false,
      // 授权对话框的显示
      grantdialogFormVisible: false,
      // 角色数据列表
      roleList: [],
      // 权限数据列表
      rightList: [],
      // 节点配置，主要配置：显示的内容属性，下一级查询数组
      defaultProps: {
        children: 'children', // 下一级会查询children
        label: 'authName' // 当前节点所展示的属性名称
      },
      // 添加角色数据对象
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑角色数据对象
      editRoleForm: {
        id: '',
        roleName: '',
        roleDesc: ''
      },
      // 新增用户的表单验证规则
      rules: {
        roleName: [
          { required: true, message: '请填写角色名称', trigger: 'blur' },
          {
            min: 1,
            max: 6,
            message: '名称长度为 1 到 6 个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 封装初始化函数
    init () {
      // 获取角色列表
      getAllRoleList()
        .then(res => {
          // console.log(res, 'getAllRoleList')
          if (res.data.meta.status === 200) {
            this.roleList = res.data.data
          }
        })
        .catch(err => {
          console.log(err)
        })
    },

    // 删除指定角色的指定权限
    // 如果是删除三级权限，那么仅仅删除三级权限，如果删除二级权限，那么也会删除对应的三级权限，如果删除一级权限也会删除对应的二级权限
    delRight (row, rightId) {
      delRightById(row.id, rightId)
        .then(res => {
          console.log(res, 'delRightById')
          this.$message.success(res.data.meta.msg)
          // 重置当前展开行数据的数据源数组
          row.children = res.data.data
        })
        .catch(err => {
          this.$message.error(err.data.meta.msg)
        })
    },
    // 展示授权对话框
    showGrantDialog (row) {
      // console.log(row, 'row')
      this.roleId = row.id
      // console.log(this.roleId)
      this.grantdialogFormVisible = true
      getAllRightList('tree')
        .then(res => {
          if (res.data.meta.status === 200) {
            console.log(res.data.meta.msg)
            this.rightList = res.data.data
          }
        })
        .catch(err => {
          console.log(err.data.meta.msg)
        })
      this.checkedArr = []
      row.children.forEach(value1 => {
        if (value1.children && value1.children.length > 0) {
          value1.children.forEach(value2 => {
            if (value2.children && value2.children.length > 0) {
              value2.children.forEach(value3 => {
                this.checkedArr.push(value3.id)
              })
            }
          })
        }
      })
    },
    // 角色授权提交
    grantRightSubmit () {
      var arr = this.$refs.mytree.getCheckedNodes()
      //  [{id:109,pid:'107,102},{id:154,pid:'107,102}]
      // console.log(arr, 'arr')
      var temp = []
      // 遍历，拼接
      for (var i = 0; i < arr.length; i++) {
        temp.push(arr[i].id + ',' + arr[i].pid)
      }
      //   ['109,107,102', '154,107,102']
      // console.log(temp, 'temp')
      var str = temp.join(',')
      //   '109,107,102,154,107,102'
      // console.log(str, 'str')
      var arr2 = str.split(',')
      //   [109,107,102, 154,107,102]
      // console.log(arr2, 'arr2')
      var finalArr = [...new Set(arr2)]
      //   new Set:数组去重 new Set:{109,107,102,154}
      //   ...可以将对象的成员展开为一个一个值 [109,107,102,154]
      //  两步合并[...new Set(arr2)]
      // console.log(finalArr, 'finalArr')
      grantRightByRole(this.roleId, finalArr.join(','))
        .then(res => {
          if (res.data.meta.status === 200) {
            this.$message.success('授权成功')
            this.grantdialogFormVisible = false
            this.init()
          }
        })
        .catch(err => {
          console.log(err.data.meta.msg)
        })
    },
    // 添加角色
    addRoleSubmit () {
      // 再次验证表单
      this.$refs.addRoleForm.validate(valid => {
        // 如果通过验证就调用接口
        if (valid) {
          addRole(this.addRoleForm.roleName, this.addRoleForm.roleDesc)
            .then(res => {
              if (res.data.meta.status === 201) {
                // 关闭对话框
                this.addRoleDialogFormVisible = false
                // 重置表单
                this.$refs.addRoleForm.resetFields()
                // 提示信息
                this.$message.success(res.data.meta.msg)
                // 刷新数据
                this.init()
              } else {
                this.$message.error(res.data.meta.msg)
              }
            })
            .catch(err => {
              console.error(err)
              this.$message.error(err.data.meta.msg)
            })
        }
      })
    },
    // 删除角色
    delRole (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        // 点击确定的回调函数
        .then(() => {
          // 调用接口
          delRoleById(id)
            // 成功的回调函数
            .then(res => {
              if (res.data.meta.status === 200) {
                this.$message.success(res.data.meta.msg)
                this.init()
              }
            })
            // 失败的回调函数
            .catch(err => {
              console.log(err.data.meta.msg)
              this.$message.error('删除失败')
            })
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 展示编辑对话框
    showRoleEdit (row) {
      this.editRoleDialogFormVisible = true
      this.editRoleForm.roleName = row.roleName
      this.editRoleForm.roleDesc = row.roleDesc
      this.editRoleForm.id = row.id
    },
    // 编辑角色
    editRoleSubmit () {
      this.$refs.editRoleForm.validate(valid => {
        if (valid) {
          editRoleById(this.editRoleForm).then(res => {
            // console.log(res, 'editRoleById')
            if (res.data.meta.status === 200) {
              this.editRoleDialogFormVisible = false
              this.$message.success('编辑成功')
              this.init()
            }
          }).catch(err => {
            console.log(err)
            this.$message.error(err.data.meta.msg)
          })
        } else {
          this.$message.error('角色输入不合法')
        }
      })
    }
  },
  mounted () {
    this.init()
  }
}
</script>

<style lang="less" scoped>
.role_search {
  margin: 15px 0;
  margin-right: 15px;
  width: 500px;
}
</style>
